<?php

/**
 *
 * Rent manager
 */

class RentManager extends DatabaseHelper {
	private $new_user = false;

	function __construct() {
		parent::__construct();
	}
	
	/**
	 * Get all users
	 *
	 * @return all users
	 */
	
	public function getAllUsers() {
		$list = array();
		if ( $this->isConnected() ) {
			$result = $this->query( 'select * from rentijad ORDER BY eesnimi, perenimi ASC');
			if ( $result ) {
				while( $row = mysql_fetch_object( $result ) ) {
					$list[] = new User( $row );
				}
			}
		}
		return $list;
	}
	
	/**
	 * This method returns users who's firstname is LIKE and lastname is LIKE
	 *
	 * @return array of User
	 */
	
	public function getUserLike( $like_value ) {
		$list = array();
		if ( $this->isConnected() ) {
			$result = $this->query( 'SELECT *, CONCAT_WS(" ", eesnimi, perenimi) AS nimi FROM rentijad HAVING nimi LIKE "%'.$this->escape( $like_value ).'%" ORDER BY nimi ASC');
			if ( $result ) {
				while( $row = mysql_fetch_object( $result ) ) {
					$list[] = array( 'id'=> $row->rentija_id, 'name' => $row->eesnimi.' '.$row->perenimi, 'email' => $row->email, 'phone' => $row->tel );
				}
			}
		}
		header('Content-type: text/json; charset=utf-8');
		echo json_encode( $list );
	}
	
	/**
	 * Delete user from database
	 */
	 
	 public function deleteUser() {
	 	if ( $this->isConnected() ) {
	 		//TODO
	 	}
	 }
	 
	 /**
	  * Get 5 last devices what user has rented
	  *
	  * @return array of devices
	  */
	
	function getRecentUserDevices( $user ) {
		$list = array();
		if ( $this->isConnected() ) {
			$result = $this->query( 'SELECT mudel, seerianumber, kirjeldus, hind FROM seadmed, renditud WHERE seadmed_id = seadme_id AND rentijad_id = "'.$user->getID().'" GROUP BY seadmed_id ORDER BY tagastatud DESC LIMIT 5' );
			if ( $result ) {
				while( $row = mysql_fetch_object( $result ) ) {
					$list[] = new Device( $row );
				}
			}
		}
		return $list;
	}
	
	/**
	 * Get user by ID
	 *
	 * @return new User or false;
	 */
	
	function getUserByID( $user_id ) {
		if ( $this->isConnected() ) {
			$result = $this->query( 'SELECT * FROM rentijad WHERE rentija_id = "'.$this->escape( $user_id ).'" LIMIT 1' );
			if ( $result ) {
				$obj = mysql_fetch_object( $result );
				if ( $obj ) {
					return new User( $obj );
				}
			}
		}
		return false;
	}
	
	/**
	 * Add user
	 */
	
	function addUser( $name, $email, $phone ) {
		if ( $this->isConnected() ) {
			$name_parts = explode(' ', ucwords( $name ) );
			$result = $this->query( 'INSERT INTO rentijad (eesnimi, perenimi, email, tel) VALUES("'.$this->escape( $name_parts[0] ).'", "'.$this->escape( $name_parts[1] ).'", "'.$this->escape( $email ).'", "'.$this->escape( $phone ).'")' );
			if ( $result ) {
				return mysql_insert_id();
			}
		}
		return false;
	}
	
	/**
	 * Modify user
	 */
	
	function updateUser( $user, $new_email, $new_phone ) {
		if ( $this->isConnected() ) {
			if ( $user->getEmail() !== $new_email ) {
				$this->query( 'UPDATE rentijad SET email = "'.$this->escape( $new_email ).'" WHERE rentija_id = "'.$user->getID().'"' );
			}
			if ( $user->getPhone() !== $new_phone ) {
				$this->query( 'UPDATE rentijad SET tel = "'.$this->escape( $new_phone ).'" WHERE rentija_id = "'.$user->getID().'"' );
			}
		}
	}
	
	/**
	 * Add rent query
	 */
	
	function finishRent( $device_id, $user_id, $return_date ) {
		if ( $this->isConnected() ) {
			if ( $this->getLastUserID() ) {
				$user_id = $this->getLastUserID();
			} 
			$user = $this->getUserByID( $user_id );
			if ( !$user ) {
				$user_id = $this->addUser( $_POST['user_name'], $_POST['user_email'], $_POST['user_phone'] );
				$this->new_user_id = $user_id;
			} else {
				$this->updateUser( $user, $_POST['user_email'], $_POST['user_phone'] );
			}
			return $this->query( 'INSERT INTO renditud (seadmed_id, rentijad_id, tagastamine) VALUES("'.$this->escape( $device_id ).'", "'.$this->escape( $user_id ).'", "'.strtotime( $this->escape( $return_date ) ).'") ');
		}
		return false;
	}
	
	/**
	 * Add contract */
	 
	function addContract( $user_id, $devices_ids ) {
		if ( $this->isConnected() ) {
			if ( $user_id == 0 ) {
				$user_id = $this->getLastUserID();
			}
			if ( $user_id > 0 ) {
				$result = $this->query( 'INSERT INTO lepingud (rentijad_id, seadmete_ids) VALUES("'.$this->escape( $user_id ).'", "'.implode( ',', $devices_ids ).'")' );
				if ( $result ) {
					return mysql_insert_id();
				}
			}
		}
		return false;
	}
	
	/**
	 * Get last rent new user id
	 */
	
	function getLastUserID() {
		if ( $this->new_user_id ) {
			return $this->new_user_id;
		}
		return false;
	}
	
	/**
	 * Get all contracts
	 */
	
	function getAllContracts() {
		$list = array();
		if ( $this->isConnected() ) {
			foreach( $this->getAllUsers() as $user ) {
				$result = $this->query( 'SELECT lepingud.id as lepingu_id, renditud_id, mudel, seerianumber, hind, UNIX_TIMESTAMP(renditud_alates) as renditud_alates, tagastamine, UNIX_TIMESTAMP(kuupaev) as lepingu_date FROM seadmed, renditud, lepingud WHERE seadmed_id = seadme_id AND FIND_IN_SET(seadmed_id, seadmete_ids) AND lepingud.rentijad_id = "'.$user->getID().'" ORDER BY renditud_alates DESC' );
				if ( $result ) {
					$current_contract_id = 0;
					$contract = false;
					while( $row = mysql_fetch_object( $result ) ) {
						if ( $current_contract_id != $row->lepingu_id ) {
							//If contract var not false, add it to the list
							if ( $contract ) {
								$list[] = $contract;
							}
							$contract = new Contract( $row->lepingu_id, $row->lepingu_date );
							$contract->setUser( $user );
							$current_contract_id = $contract->getID();
						}
						$contract->addDevice( new Device( $row ) );
					}
					//Add last contract after while cycle has quitted
					if ( $contract ) {
						$list[] = $contract;
					}
				}
			}
		}
		return $list;
	}
	
	/**
	 * Get contract by ID
	 *
	 * @return Contract object or false
	 */
	
	function getContractByID( $id = false ) {
		$contract = false;
		if ( $this->isConnected() ) {
			if ( $id ) {
				$result = $this->query( 'SELECT lepingud.id as lepingu_id, renditud_id, mudel, seerianumber, hind, eesnimi, perenimi, email, tel, UNIX_TIMESTAMP(renditud_alates) as renditud_alates, tagastamine, UNIX_TIMESTAMP(kuupaev) as lepingu_date FROM seadmed, rentijad, renditud, lepingud WHERE seadmed_id = seadme_id AND FIND_IN_SET(seadmed_id, seadmete_ids) AND lepingud.rentijad_id = rentija_id AND renditud.rentijad_id = rentija_id AND id = "'.$this->escape( $id ).'" ORDER BY renditud_alates DESC' );
				if ( $result ) {
					while ( $row = mysql_fetch_object( $result ) ) {
						if ( !$contract ) {
							$contract = new Contract( $row->lepingu_id, $row->lepingu_date );
							$contract->setUser( new User( $row ) );
						}
						$contract->addDevice( new Device( $row ) );
					}
				}
			}
		}
		return $contract;
	}
}

class Contract {
	private $devices = array();
	
	function __construct( $contract_id, $contract_date ) {
		$this->id = $contract_id;
		$this->contract_date = $contract_date;
	}
	
	function addDevice( $device ) {
		$this->devices[] = $device;
	}
	
	function getDevices() {
		return $this->devices;
	}
	
	function setUser( $user ) {
		$this->user = $user;
	}
	
	function getPDFName() {
		return 'seadmete-laenuleping-'.$this->getStringID();
	}
	
	function getStringID() {
		return $this->getID().'-'.strftime( '%d%m%Y', $this->contract_date );
	}
	
	function getID() {
		return $this->id;
	}
	
	function getUser() {
		return $this->user;
	}
	
	function getDate() {
		return strftime( '%d.%m.%Y, %H:%M', $this->contract_date );
	}
	
	function getReturnDate() {
		$devices = $this->getDevices();
		if ( isSet( $devices[0] ) ) {
			return $devices[0]->getReturnDate(true);
		}
		return;
	}
}


class User {
	
	private $firstname, $lastname, $email, $tel;
	
	function __construct( $row ) {
		if ( isSet( $row->rentija_id ) ) {
			$this->id = $row->rentija_id;
		}
		$this->firstname = $row->eesnimi;
		$this->lastname = $row->perenimi;
		$this->email = $row->email;
		$this->tel = $row->tel;
	}
	
	function getID() {
		return $this->id;
	}
	
	function getFullname() {
		return $this->getFirstname().' '.$this->getLastname();
	}
	
	function getFirstname() {
		return $this->firstname;
	}
	
	function getLastname() {
		return $this->lastname;
	}
	
	function getEmail() {
		if ( $this->hasEmail() ) {
			return $this->email;
		}
		return '-';
	}
	
	function getPhone() {
		if ( $this->hasPhone() ) {
			return $this->tel;
		}
		return '-';
	}
	
	function hasEmail() {
		return !empty( $this->email );
	}
	
	function hasPhone() {
		return !empty( $this->tel );
	}
}

?>